package makovo.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class Comm {
	private HttpGet mGet;
	private HttpParams mParams;
	private DefaultHttpClient mClient;
	private HttpResponse mClientResponse;

	private final String mUri;
	private final int timeOutConn = 10000;
	private final int timeOutSocket = 10000;

	public Comm(String uri) {
		this.mUri = uri;
	}

	private HttpEntity getEntity(String method) throws ClientProtocolException, IOException {
		char[] buffer = null;
		HttpEntity entity;

		mGet = new HttpGet(mUri + method);
		mParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(mParams, timeOutConn);
		HttpConnectionParams.setSoTimeout(mParams, timeOutSocket);

		mGet.setHeader("Accept", "application/json");
		mGet.setHeader("Content-type", "application/json");

		mClient = new DefaultHttpClient(mParams);
		mClientResponse = mClient.execute(mGet);

		entity = mClientResponse.getEntity();

		return entity;
	}

	public String getStringResponse(String method) throws ClientProtocolException, IOException {
		HttpEntity entity = getEntity(method);
		String res = null;

		InputStreamReader reader = new InputStreamReader(entity.getContent());
		StringWriter writer = new StringWriter();

		IOUtils.copy(reader, writer);

		res = writer.toString();

		writer.close();
		reader.close();

		return res;
	}
}
